package net.wenku8.reader.util

enum class TextType (val reg : Regex, val msg : String? = null){
    A(Regex("[a-zA-Z]*"), "必须为字母"),
    N(Regex("[0-9]*"),"必须为数字"),
    AN(Regex("[a-zA-Z0-9]*"),"必须为字母数字"),
    ANS(Regex("[\\x21-\\x7E]*"),"必须为字母数字或特殊字符"),
    CN(Regex("[一-龥]"),"必须为汉字"),
    PHONE(Regex("1[3-9]\\d{9}")),
    EMAIL(Regex("((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})(\\.((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})){3}")),
}

class ValidateRule(
    val value : String? = null,
    val name : String,
    val required : Boolean = false,
    val type : TextType? = null,
    val max : Int? = null,
    val min : Int? = null,
    val reg : String? = null,
    val regMsg :String? = null
)

fun checkRule(ruleList : List<ValidateRule>) : String?{
    for(rule in ruleList){
        if (rule.required){
            if (rule.value == null || rule.value.trim().isEmpty()){
                return rule.name + "不能为空"
            }
        }
        if (rule.value != null){
            if (rule.type != null){
                if (!rule.type.reg.matches(rule.value.toString())){
                    return rule.type.msg ?: (rule.name + "格式错误")
                }
            }
            if(rule.reg != null){
                if (!Regex(rule.reg).matches(rule.value.toString())){
                    return rule.regMsg ?: (rule.name + "格式错误")
                }
            }
            if(rule.max != null){
                if(rule.value.length > rule.max) {
                    return rule.name + "长度最大为"+rule.max
                }
            }
            if(rule.min != null){
                if(rule.value.length < rule.min) {
                    return rule.name + "长度最小为"+rule.min
                }
            }
        }
    }
    return null
}